<?php


namespace app\common\controller;

/**
 * Util工具类
 * Class Util
 * @package app\common\controller
 */
class Util
{
    /**
     * 生成随机字符
     * @param int $length 长度
     * @param string $type 类型(支持数字、字母、字符串、全部)
     * @param int $convert 转换大小写
     * @return string
     */
    public static function random($length = 6, $type = 'string', $convert = 0)
    {
        $config = array(
            'number' => '1234567890',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ2345678',
            'all' => 'abcdefgh∫ijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if (!isset($config[$type])) $type = 'string';
        $string = $config[$type];

        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string{mt_rand(0, $strlen)};
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

    /**
     * 通过IP获取地理位置
     * @param $ipAddr
     * @return string
     */
    public static function get_location_by_ip($ipAddr): string
    {
        $key = config('person.tencent_map_api_key');
        $url = 'http://apis.map.qq.com/ws/location/v1/ip?ip=';
        $res = json_decode(file_get_contents($url . $ipAddr . '&key=' . $key));
        return $res->status === 375 ? $res->message : '测试';
    }
}